package org.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.atguigu.gmall.realtime.app.BaseApp;
import org.atguigu.gmall.realtime.bean.TradePaymentBean;
import org.atguigu.gmall.realtime.common.Constant;
import org.atguigu.gmall.realtime.util.AtguiguUtil;
import org.atguigu.gmall.realtime.util.FlinkSinkUtil;

import java.time.Duration;

/**
 * Project:gmallRealTime
 * Package:org.atguigu.gmall.realtime.app.dws
 * Author: ZengHaiFeng
 * CreateTime:2023/5/5 08:13:58
 * Description: Todo
 * Version：1.0
 */
public class Dws_07_DwsTradePaymentSucWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_07_DwsTradePaymentSucWindow()
                .init(40007,2,
                        Constant.TOPIC_DWD_TRADE_PAY_DETAIL_SUC,"Dws_07_DwsTradePaymentSucWindow");
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        ds.map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((obj,ts) -> obj.getLong("ts")*1000)
                                .withIdleness(Duration.ofSeconds(60)))
                .keyBy(obj -> obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentBean>() {
                    private ValueState<String> lastPaySucDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastPaySucDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("lastPaySucDate", String.class)
                        );
                    }

                    @Override
                    public void processElement(
                            JSONObject value,
                            Context ctx,
                            Collector<TradePaymentBean> out) throws Exception {
                        String lastPaySucDate = lastPaySucDateState.value();
                        String today = AtguiguUtil.tsToDateTime(value.getLong("ts") * 1000);
                        Long paymentSucUniqueUserCount = 0L;
                        Long paymentSucNewUserCount = 0L;

                        if (lastPaySucDate == null){
                            paymentSucNewUserCount = 1L;
                            paymentSucUniqueUserCount = 1L;
                            lastPaySucDateState.update(today);
                        }else {
                            if (!today.equals(lastPaySucDate)){
                                paymentSucUniqueUserCount = 1L;
                                lastPaySucDateState.update(today);
                            }
                        }
                        if (paymentSucNewUserCount != 0L || paymentSucUniqueUserCount != 0L){
                            out.collect(new TradePaymentBean("","",
                                    paymentSucUniqueUserCount,
                                    paymentSucNewUserCount,value.getLong("ts")*1000));
                        }
                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .aggregate(new AggregateFunction<TradePaymentBean, TradePaymentBean, TradePaymentBean>() {
                    @Override
                    public TradePaymentBean createAccumulator() {
                        return new TradePaymentBean(
                                "",
                                "",
                                0L,
                                0L,
                                0L);
                    }

                    @Override
                    public TradePaymentBean add(TradePaymentBean value, TradePaymentBean accumulator) {
                        accumulator.setPaymentSucUniqueUserCount(accumulator.getPaymentSucUniqueUserCount() + value.getPaymentSucUniqueUserCount());
                        accumulator.setPaymentSucNewUserCount(accumulator.getPaymentSucNewUserCount() + value.getPaymentSucNewUserCount());
                        return accumulator;
                    }

                    @Override
                    public TradePaymentBean getResult(TradePaymentBean accumulator) {
                        return accumulator;
                    }

                    @Override
                    public TradePaymentBean merge(TradePaymentBean a, TradePaymentBean b) {
                        return null;
                    }
                },
                    new ProcessAllWindowFunction<TradePaymentBean, TradePaymentBean, TimeWindow>() {
                        @Override
                        public void process(
                                Context context,
                                Iterable<TradePaymentBean> elements,
                                Collector<TradePaymentBean> out) throws Exception {
                            TradePaymentBean bean = elements.iterator().next();
                            bean.setStt(AtguiguUtil.tsToDateTime(context.window().getStart()));
                            bean.setEdt(AtguiguUtil.tsToDateTime(context.window().getEnd()));
                            bean.setTs(System.currentTimeMillis());
                            out.collect(bean);
                        }
                    })
                .addSink(FlinkSinkUtil.getClickHouseSink(
                            "dws_trade_payment_suc_window", TradePaymentBean.class));
    }
}
